package mirrormonkey.framework.parameter;

import mirrormonkey.framework.EntityProvider;
import mirrormonkey.framework.entity.EntityData;
import mirrormonkey.framework.entity.SyncEntity;

import com.jme3.network.MessageConnection;

public class IdentityAwareInterpreter implements ParameterInterpreter {

	private final EntityProvider entityProvider;

	public IdentityAwareInterpreter(EntityProvider entityProvider) {
		this.entityProvider = entityProvider;
	}

	@Override
	public Object extractData(Object object) {
		EntityData data = entityProvider.getData((Integer) object);
		return data == null ? null : data.getEntity();
	}

	@Override
	public Object packData(Object object) {
		SyncEntity s = (SyncEntity) object;
		EntityData d = s == null ? null : s.getData();
		return d == null ? EntityProvider.NULL_ID : d.getId();
	}

	@Override
	public Class<?> fetchClass(MessageConnection connection, Object parameter) {
		// TODO throw more detailled exception if parameter is an entity but not
		// registered at all
		return parameter == null ? null : ((SyncEntity) parameter).getData()
				.getStaticData(connection).connectedClass;
	}

	@Override
	public boolean applies(Object parameter) {
		return SyncEntity.class.isInstance(parameter);
	}
}
